var profiles = [];
var currentProfileId;

$(document).ready(function () {

	$(document).on('profilesLoaded', function(e) {
		$(profiles).each(function () {
			var profileOptionLi = $('<li>');
			profileOptionLi.append($('<a>').attr('profile', this.id).attr('tab-index',-1).attr('href','#').text(this.name).click(profileButtonListener));
			$('ul.dropdown-menu').append(profileOptionLi);
		});
	
		var lastProfile = localStorage.getItem('lastProfile');
		var profileId = 'basic';
		if (lastProfile != undefined) {
			if (lastProfile.length > 0) {
				profileId = lastProfile;
			}
		}
		switchToProfile(profileId);
	});
	
	loadProfiles();
});

function profileButtonListener(obj) {
	switchToProfile($(obj.target).attr('profile'));
}

function loadProfiles() {
	var pathname = window.location.pathname.substring(0, window.location.pathname.lastIndexOf("/") + 1);
    var origin = window.location.origin;

    if (!origin) {
        origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
    }

    var xmlLoc = origin + pathname + "data/profiles.xml";
	
		$.ajax({
        type: "GET",
        url: xmlLoc,
        dataType: "xml",
        success: function (xml) {
            $xml = $(xml);
			
		
			//create the basis for repetition
			var emptySpan = $("<span>").addClass("col-xs-1").addClass("col-3");
			var emptySpan2 = $("<span>").addClass("col-xs-2").addClass("col-3");
			var emptyRow = $("<div>").addClass("row").addClass("empty-row");
			
			
			var sourceUnitSpan = $("<span>").addClass("col-xs-2").addClass("col-3");
			$(sourceUnitSpan).append(
				$("<input>").addClass("form-control").attr("type","text").attr("placeholder","SourceUnit")
			);
			
			var destinationUnitSpan = $('<div>').addClass('col-xs-2').append(
				$('<div>').addClass('input-group').append(
					$("<input>").addClass('destination-unit').addClass("form-control").attr("type","text").attr("placeholder","DestinationUnit")
				).append(
					$('<span>').addClass('input-group-btn').append(
						$('<button>').addClass('btn').addClass('btn-default').attr('type','button').text('+').hide()
					)
				)
			);
			
			$(destinationUnitSpan).find("input").attr("placeholder","DestinationUnit");
			
			var sourceValueSpan = $(sourceUnitSpan).clone();
			$(sourceValueSpan).find("input").attr("placeholder","SourceValue");
			
			var destinationValueSpan = $(sourceUnitSpan).clone()
			$(destinationValueSpan).find("input").attr("placeholder", "DestinationValue");
			
			
            //READING LOOP
			  
            $xml.find('profile').each(function (pindex) {
				//prepare container for all profile DOM elements
				var profile = {};
				profile.id = $(this).attr("id");
				profile.name = $(this).attr("name");
				
				//loop through profile's source boxes
				$(this).find('source').each(function (sindex) {
					var source = {};
					source.unit = $(this).attr("unit");
					source.destvaluebox = "";
					source.destbox = "";
					var destinations = [];
					// first pass creates each of the destination spans
					$(this).find('destination').each(function (dindex) {
						destination = {};
						destination.id = sindex + "-" + dindex;
						destination.unit = $(this).attr('unit');
						destination.valueSpan = $(destinationValueSpan).clone();
						destination.valueInput = $(destination.valueSpan).find('input')
							.attr('unit-box', 'destination-unit-' + destination.id)
							.attr('id', 'destination-value-' + destination.id);
							
						destination.unitSpan = $(destinationUnitSpan).clone();
						destination.unitInput = $(destination.unitSpan).find('input')
							.attr('value-box', 'destination-value-' + destination.id)
							.attr('source-box', 'source-unit-' + sindex)
							.attr('id', 'destination-unit-' + destination.id)
							.val(destination.unit);
						
						destinations[dindex] = destination;
						 
						if (dindex > 0) {
							source.destvaluebox += ',';
						}
						source.destvaluebox += 'destination-value-' + destination.id;
					});
					
					// second pass adds all properties to each other:
					for (i = 0; i < destinations.length; i++) {
						var destvaluebox = "source-value-" + sindex + ",";
						destvaluebox += source.destvaluebox;
						var search = 'destination-value-' + destinations[i].id;
						destvaluebox = destvaluebox.replace(search, '');
						destvaluebox = destvaluebox.replace(',,', ',');
						destvaluebox = destvaluebox.replace(/(^,)|(,$)/g, "");
						
						destinations[i].valueInput = $(destinations[i].valueInput).attr('dest-value-box', destvaluebox);
						var destbox = destvaluebox.replace('value', 'unit');
						destinations[i].valueInput = $(destinations[i].valueInput).attr('dest-box', destbox);
					}
					
					source.destbox = source.destvaluebox.replace('value', 'unit');
					
					var thisSourceUnitSpan = $(sourceUnitSpan).clone();
					thisSourceUnitSpan.find("input")
						.attr("value-box", "source-value-" + sindex)
						.attr("id", "source-unit-" + sindex)
						.val(source.unit);
					
					var thisSourceValueSpan = $(sourceValueSpan).clone();
					thisSourceValueSpan.find('input')
						.attr('id', 'source-value-' + sindex)
						.attr('dest-box', source.destbox)
						.attr('dest-value-box', source.destvaluebox)
						.attr('unit-box', "source-unit-" + sindex);
					
					var row = $("<div>").addClass("row").append(
						$(emptySpan).clone()
					).append(
						thisSourceUnitSpan
					).append(
						thisSourceValueSpan
					).append(
						$(emptySpan2).clone()
					).append(
						destinations[0].unitSpan
					).append(
						destinations[0].valueSpan
					);
					source.dom = $('<div>').append(row);
					
					if (destinations.length > 1) {
						
						for (i = 1; i < destinations.length; i++) {
							var nrow = $("<div>").addClass("row").append(
							  $(emptySpan).clone()
							).append(
							  $(emptySpan2).clone()
							).append(
							  $(emptySpan2).clone()
							).append(
							  $(emptySpan2).clone()
							).append(
							  destinations[i].unitSpan
							).append(
							  destinations[i].valueSpan
							).append(
							  $(emptySpan).clone()
							);
							
							source.dom = $(source.dom).append(nrow);
						}
					}
					
					if (sindex == 0) {
						profile.dom = $('<div>').append(source.dom);
					}else {
						profile.dom = $(profile.dom).append($(emptyRow).clone()).append(source.dom);
					}
				});
				profiles.push(profile);
            });
			
			$(document).trigger('profilesLoaded');
        }
    });
	
	$( window ).resize(correctContentHeight);
}

function switchToProfile(profileId) {
	
	var profile = {};
	$(profiles).each(function () {
		if (this.id == profileId) {
			profile = this;
		}
	}).promise().done(function () {
		localStorage.setItem('lastProfile', profileId);
		
		$( "div#contentHolder .row:not(.modalrow)" ).remove();
		$( "div#contentHolder" ).append($(profile.dom).clone());
		
		correctContentHeight();
		currentProfileId = profileId;
		$(document).trigger('profileLoaded');
	});
}

function correctContentHeight() {
	var margins = 0;
	$('*:not(div#contentHolder)').each(function () {
		margins += parseInt($(this).css('margin-top'));
		margins += parseInt($(this).css('margin-bottom'));
	});
	
	var othersHeight = 0;
	$('div#main > *:not(div#contentHolder)').each(function () {
		othersHeight += $(this).height();
	});
	
	var contentHeight = $('div#contentHolder').height();
	var contentMargin = ($(window).innerHeight()
			- (contentHeight + othersHeight + margins))
		/ 2;
		
	$('div#contentHolder').css('margin-top',contentMargin).css('margin-bottom', contentMargin);
}